from flask import Blueprint, request, jsonify, current_app
from datetime import datetime
import re
from db import get_db

bp = Blueprint('niantie', __name__, url_prefix='/api/niantie')

@bp.route('/import', methods=['POST'])
def import_packages():
    """导入包裹数据的API端点"""
    try:
        data = request.get_json()
        if not data:
            return jsonify({'error': '无效的请求数据'}), 400

        # 验证必要参数
        required_fields = ['paste_text', 'batch_id', 'operator']
        for field in required_fields:
            if field not in data:
                return jsonify({'error': f'缺少必要参数: {field}'}), 400

        paste_text = data['paste_text']
        batch_id = data['batch_id']
        operator = data['operator']

        current_app.logger.info(f'开始导入包裹数据: batch_id={batch_id}, operator={operator}')

        # 获取数据库连接
        db = get_db()
        cursor = db.cursor()

        try:
            # 验证批次是否存在
            cursor.execute('SELECT status FROM batches WHERE batch_id = ?', (batch_id,))
            batch = cursor.fetchone()
            if not batch:
                return jsonify({'error': '批次不存在'}), 404
            if batch['status'] == 'closed':
                return jsonify({'error': '批次已关闭，无法导入'}), 400

            current_app.logger.info('批次验证通过')

            # 解析包裹数据 - 支持两种格式
            package_ids = []
            complex_pattern = r'包裹单号:([A-Za-z0-9]+)\s*\[UID\]:(\d+)\s*上架时间：([\d\- :]+)'
            simple_pattern = r'^([A-Za-z0-9]+)'
            
            for line in paste_text.splitlines():
                line = line.strip()
                if not line:
                    continue
                    
                # 尝试匹配复杂格式
                complex_match = re.search(complex_pattern, line)
                if complex_match:
                    package_id = complex_match.group(1)
                    uid = complex_match.group(2)
                    shelf_time = complex_match.group(3)
                    current_app.logger.debug(f'匹配到复杂格式: 包裹号={package_id}, UID={uid}, 上架时间={shelf_time}')
                    package_ids.append({
                        'package_id': package_id,
                        'uid': uid,
                        'shelf_time': shelf_time,
                        'format': 'complex'
                    })
                else:
                    # 尝试匹配简单格式
                    simple_match = re.search(simple_pattern, line)
                    if simple_match:
                        package_id = simple_match.group(1)
                        current_app.logger.debug(f'匹配到简单格式: 包裹号={package_id}')
                        package_ids.append({
                            'package_id': package_id,
                            'format': 'simple'
                        })

            if not package_ids:
                return jsonify({'error': '没有找到有效的包裹数据'}), 400

            current_app.logger.info(f'找到 {len(package_ids)} 个包裹数据')

            # 准备导入结果统计
            result = {
                'success': [],
                'exists': [],
                'invalid': [],
                'duplicates': []
            }

            # 处理每个包裹
            now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            processed_packages = set()

            for package_data in package_ids:
                package_id = package_data['package_id']

                # 检查重复
                if package_id in processed_packages:
                    result['duplicates'].append(package_id)
                    continue
                processed_packages.add(package_id)

                # 检查包裹是否已存在
                cursor.execute('SELECT package_id FROM packages WHERE package_id = ? AND batch_id = ?', 
                             (package_id, batch_id))
                
                if cursor.fetchone():
                    result['exists'].append(package_id)
                else:
                    try:
                        # 根据格式插入不同的数据
                        if package_data['format'] == 'complex':
                            cursor.execute('''
                                INSERT INTO packages (package_id, batch_id, status, operator, create_time, uid, shelf_time)
                                VALUES (?, ?, ?, ?, ?, ?, ?)
                            ''', (package_id, batch_id, 'unscanned', operator, now, 
                                 package_data['uid'], package_data['shelf_time']))
                        else:
                            cursor.execute('''
                                INSERT INTO packages (package_id, batch_id, status, operator, create_time)
                                VALUES (?, ?, ?, ?, ?)
                            ''', (package_id, batch_id, 'unscanned', operator, now))
                            
                        result['success'].append(package_id)
                    except Exception as e:
                        current_app.logger.error(f'插入包裹失败: {package_id}, 错误: {str(e)}')
                        result['invalid'].append({
                            'package_id': package_id,
                            'error': str(e)
                        })

            # 更新批次统计信息
            cursor.execute('''
                UPDATE batches 
                SET total_count = (
                    SELECT COUNT(*) FROM packages WHERE batch_id = ?
                ),
                scanned_count = (
                    SELECT COUNT(*) FROM packages WHERE batch_id = ? AND status = 'scanned'
                ),
                update_time = ?
                WHERE batch_id = ?
            ''', (batch_id, batch_id, now, batch_id))

            # 提交事务
            db.commit()

            # 获取更新后的批次统计
            cursor.execute('SELECT total_count, scanned_count FROM batches WHERE batch_id = ?', (batch_id,))
            stats = cursor.fetchone()
            
            if not stats:
                raise Exception('无法获取批次统计信息')

            current_app.logger.info(f'批次统计: total_count={stats["total_count"]}, scanned_count={stats["scanned_count"]}')
            
            # 计算完成率
            completion = round(stats['scanned_count'] / stats['total_count'] * 100) if stats['total_count'] > 0 else 0

            # 构建响应消息
            message = f"成功导入 {len(result['success'])} 个包裹"
            if result['exists']:
                message += f"，{len(result['exists'])} 个包裹已存在"
            if result['invalid']:
                message += f"，{len(result['invalid'])} 个无效包裹号"
            if result['duplicates']:
                message += f"，{len(result['duplicates'])} 个重复包裹号"

            current_app.logger.info(f'导入完成: {message}')

            return jsonify({
                'success': True,
                'message': message,
                'result': result,
                'batch_stats': {
                    'total': stats['total_count'],
                    'scanned': stats['scanned_count'],
                    'unscanned': stats['total_count'] - stats['scanned_count'],
                    'completion': completion
                }
            })

        except Exception as e:
            current_app.logger.error(f'数据库操作失败: {str(e)}')
            db.rollback()
            raise

    except Exception as e:
        current_app.logger.error(f'导入失败: {str(e)}')
        return jsonify({'error': f'导入失败: {str(e)}'}), 500 